package com.maori.languageapp.discover;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.maori.languageapp.R;
import com.maori.languageapp.adapter.Language_App_List_Exapander;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

public class Maori_Discover_Word_AudioList_Adapter  extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;

	private Activity activity;
	private Context context;
	
	private String NID;
	
	static String json = ""; 
	
	private Handler seekHandler = new Handler();
	//Handler seekHandler;
	SeekBar seek_bar;
	
	static InputStream is = null;
	HttpParams httpParameters = new BasicHttpParams();
	
	private static final int NOT_PLAYING = -1;
	private int mPlayingPosition = NOT_PLAYING;
	
	private PlaybackUpdater mProgressUpdater = new PlaybackUpdater();
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;
	
	private static byte[] buff =new byte[1024];
	private String retval="";
	
	private int nFlag;
	private int listType;
	
	private String[] NID_s;
	private String[] MID_s;
	private String[] M_Source_s;
	
	MediaPlayer player;
	
	public Maori_Discover_Word_AudioList_Adapter(Activity activity,String NID) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.NID = NID;
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Loading Audio List", "Loading",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		
		try {
			
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);			
			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			
			/*HttpPost httppost = new HttpPost(RegisterUserLink);*/
			HttpPost httppost = new HttpPost(urls[0]);
			JSONObject json = new JSONObject();
			
			json.put("record1", NID);

			JSONArray postjson = new JSONArray();
			postjson.put(json);
			httppost.setHeader("json", json.toString());
			Log.e("JSON POST AUDIO:",postjson.toString());
			httppost.getParams().setParameter("jsonpost", postjson);
			httppost.setEntity(new UrlEncodedFormEntity(
					nameValuePairs));
			HttpResponse httpResponse = httpclient.execute(httppost);
			
			HttpEntity httpEntity = httpResponse.getEntity();
			
			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
			
			/*try{
				jobj = new JSONObject(json);
				
			}catch(JSONException e){
				Log.e("User register Service","Error parsing data"+e.toString());
			}*/
			
			//return jobj;
			
		return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		progdialod.dismiss();
		
		Log.d("Post Exec", result);
		
		try {
			
			JSONObject respObj = new JSONObject(result);
			
			//JSONObject value = respObj.getJSONObject("posts");
			
			JSONArray appLink = respObj.getJSONArray("posts");
			//JSONArray appLink = new JSONArray(result);
			
			Log.e("Size", ""+appLink.length());
			
			NID_s = new String[appLink.length()];
			MID_s = new String[appLink.length()];
			M_Source_s = new String[appLink.length()];
			
				for(int i=0;i<appLink.length();i++){
					JSONObject match = appLink.getJSONObject(i);
					
					Log.e("NID DJ:", match.getString("NID"));
					Log.e("M_Source_s DJ:", match.getString("M_Source"));
					NID_s[i] = match.getString("NID");
					MID_s[i] = match.getString("MID");
					M_Source_s[i] = match.getString("M_Source");
					
				}

				ListView lstView=(ListView)activity.findViewById(R.id.listViewAudioSynonyms);
				lstView.setAdapter(new ImgViewBaseAdap(activity.getApplicationContext()));
				Language_App_List_Exapander.getListViewSize(lstView);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

	class ImgViewBaseAdap extends BaseAdapter{
		
		 private Context context;
		 LayoutInflater inflater;
		 

		public ImgViewBaseAdap(Context context) {
			this.context = context;
			this.inflater = LayoutInflater.from(context);
			player = new MediaPlayer();
			player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			
		}
		
		@Override
		public View getView(int position,View convertView,ViewGroup parent){
			
			ViewHolder holder;
			final int pospass = position;
			
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.languageapp_discover_audio, null);
                holder = new ViewHolder();
                
                holder.textView = (TextView)convertView.findViewById(R.id.addnew);
                holder.play_button = (Button)convertView.findViewById(R.id.Discover_example_playaudio);
                holder.pause_button = (Button)convertView.findViewById(R.id.Discover_example_mute);
                holder.seek_bar = (SeekBar) convertView.findViewById(R.id.seek_bar);
                
                seek_bar = holder.seek_bar;
                
                try {
        			player.setDataSource(M_Source_s[position]);
        			player.prepare();
        		} catch (IllegalArgumentException e) {
        			e.printStackTrace();
        		} catch (SecurityException e) {
        			e.printStackTrace();
        		} catch (IllegalStateException e) {
        			e.printStackTrace();
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
                
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
			
			//////////////////////
			
			if (position == mPlayingPosition) {
                //pb.setVisibility(View.VISIBLE);
                mProgressUpdater.mBarToUpdate = holder.seek_bar;
                seekHandler.postDelayed(mProgressUpdater, 100);
            } else {
                //pb.setVisibility(View.GONE);
            	holder.seek_bar.setProgress(0);
                if (mProgressUpdater.mBarToUpdate == holder.seek_bar) {
                    //this progress would be updated, but this is the wrong position
                    mProgressUpdater.mBarToUpdate = null;
                }
            }
			
			//////////////////////
			
			holder.textView.setText(NID_s[position]);
			
			holder.play_button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					 try {
						 	player.reset();
						 	player.setDataSource(M_Source_s[pospass]);
						 	player.prepare();
						 	player.start();
				            mPlayingPosition = pospass;

				            seekHandler.postDelayed(mProgressUpdater, 500);

				            //trigger list refresh, this will make progressbar start updating if visible
				            notifyDataSetChanged();
				        } catch (IOException e) {
				            //Log.e(TAG, "unable to play: " + mSongs.get(position));
				            e.printStackTrace();
				            stopPlayback();
				        }
					
					//player.start();
				}
			});
			
			holder.pause_button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					player.pause();
				}
			});
			
            return convertView;
		}

		@Override
		public int getCount() {
			return NID_s.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		
	}

	public static class ViewHolder {
        public TextView textView;
        public ImageView imageVw;
        public SeekBar seek_bar;
        public Button play_button, pause_button, stop_button;
        
    }

    
    private class PlaybackUpdater implements Runnable {
        public SeekBar mBarToUpdate = null;

        @Override
        public void run() {
            if ((mPlayingPosition != NOT_PLAYING) && (null != mBarToUpdate)) {
                mBarToUpdate.setProgress( (100*player.getCurrentPosition() / player.getDuration()) );
                seekHandler.postDelayed(this, 500);
            } else {
                //not playing so stop updating
            }
        }
    }
    
    private void stopPlayback()
    {
        mPlayingPosition = NOT_PLAYING;
        mProgressUpdater.mBarToUpdate = null;
        player.stop();
    }
	
}
